<?php

namespace app\api\controller\app;

use addons\epay\library\Service;
use app\admin\model\Article;
use app\admin\model\Articletype;
use app\admin\model\City;
use app\admin\model\Shop;
use app\admin\model\Shopcharge;
use app\admin\model\Shopchargeconfig;
use app\admin\model\Shopjoin;
use app\admin\model\Shopmeituan;
use app\admin\model\Shoporder;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproom;
use app\admin\model\Shoptableorder;
use app\admin\model\Shoptuan;
use app\admin\model\Tuanorder;
use app\admin\model\Userbalance;
use app\admin\model\Usermeituancode;
use app\admin\model\Userorderprofit;
use app\admin\model\Usertuan;
use app\admin\model\Userweixin;
use app\api\service\MtService;
use app\api\service\MtUtil;
use app\api\service\XhtMtService;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Http;
use fast\Random;
use think\Config;
use think\Validate;
use Yansongda\Pay\Pay;

/**
 */
class Meituan extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';
    protected $appKey = "";
    protected $secret = "";
    protected $developerId = 113890;
    protected $signKey = "1w7bp3gttce7iytc";
    public function _initialize()
    {
        parent::_initialize();
        $this->appKey = "2c8bce9314172fc1";
        $this->secret = "bb39c01023ce0fbb519d2b68f4457ec37fbc0e6a";
    }

    public function auth()
    {
        $developerId = $this->developerId;
        $signKey = $this->signKey;
        $code = $_GET["code"];
        $businessId = 58;
        $charset = "UTF-8";
        $grantType = "authorization_code";
        $timestamp = time();
        $param = array();
        $param['businessId'] = $businessId;
        $param['charset'] = $charset;
        $param['code'] = $code;
        $param['developerId'] = $developerId;
        $param['grantType'] = $grantType;
        $param['timestamp'] = $timestamp;
        $param['sign'] = $this->get_sign($signKey,$param);

        $url = "https://api-open-cater.meituan.com/oauth/token";

        error_log("==mt=param===".json_encode($param));
        $result = $this->curl_post($url,$param);
        if($result['code'] == 0){
            $accessToken = $result['data']['accessToken'];
            $expireIn = $result['data']['expireIn'];
            $refreshToken = $result['data']['refreshToken'];
            $opBizName = $result['data']['opBizName'];
            $opBizCode = $result['data']['opBizCode'];

            $shopModel = new Shop();
            $shop = $shopModel->where('mt2_biz_code',$opBizCode)->find();
            if(!$shop){
                $shop = $shopModel->where('mt_name',$opBizName)->find();
                if(!$shop) $this->error("店铺不存在");
            }
            $shopModel->where('id',$shop['id'])->update(['mt2_token'=>$accessToken,'mt2_refresh_token'=>$refreshToken,'mt2_update_time'=>strtotime("+ ".$expireIn." seconds"),'mt2_biz_code'=>$opBizCode]);

            $this->success("授权成功");
        }else{
            $this->error($result['message']);
        }


    }

    public function refreshToken($refreshToken)
    {

        $developerId = $this->developerId;
        $signKey = $this->signKey;
        $businessId = 58;
        $charset = "UTF-8";
        $grantType = "refresh_token";
        $timestamp = time();
        $mtUtil = new MtUtil();
        $param = array();
        $param['businessId'] = $businessId;
        $param['charset'] = $charset;
        $param['scope'] = "all";
        $param['developerId'] = $developerId;
        $param['grantType'] = $grantType;
        $param['timestamp'] = $timestamp;
        $param['refreshToken'] =$refreshToken;
        $param['sign'] = $this->get_sign($signKey,$param);

        $url = "https://api-open-cater.meituan.com/oauth/refresh";

        $result = $this->curl_post($url,$param);
        if($result['code'] == 0){
            $accessToken = $result['data']['accessToken'];
            $expireIn = $result['data']['expireIn'];
            $refreshToken = $result['data']['refreshToken'];
            $opBizName = $result['data']['opBizName'];
            $opBizCode = $result['data']['opBizCode'];

        }else{
            $this->error($result['message']);
        }
    }


    public function getShopProductList()
    {

        $url = "https://api-open-cater.meituan.com/ddzh/tuangou/deal/queryshopdeal";

        $param = array();
        $param['businessId'] = 58;
        $param['charset'] = "UTF-8";
        $param['appAuthToken'] = "V2-4c997fa56983d6aa840022ed7906c5a112c7ff64b12c04d3a5c4e373a0776cd0a1d4c69e8784c345b94f8d998fc630aa69abb2d52f7eff4ef1a7514100f80a90adf2a43242c732663988ee9f9c2d308a";
        $param['timestamp'] = time();
        $param['developerId'] = $this->developerId;
        $param['version'] = 2;

        $biz = array();
        $biz['offset'] = 1;
        $biz['limit'] = 100;
        $biz['source'] = 2;

        $param['biz'] = json_encode($biz);
        $param['sign'] = $this->get_sign($this->signKey,$param);

        $result = $this->curl_post($url,$param);

        $this->success('',$result);

    }

    public function prepare($req)
    {

        $url = "https://api-open-cater.meituan.com/ddzh/tuangou/receipt/prepare";

        $shopModel = new Shop();
        $shop = $shopModel->where('id',$req['shop_id'])->find();

        $param = array();
        $param['businessId'] = 58;
        $param['charset'] = "UTF-8";
        $param['appAuthToken'] = $shop['mt2_token'];
        $param['timestamp'] = time();
        $param['developerId'] = $this->developerId;
        $param['version'] = 2;

        $biz = array();
        $biz['receiptCode'] = $req['code'];
        $param['biz'] = json_encode($biz);
        $param['sign'] = $this->get_sign($this->signKey,$param);

        $result = $this->curl_post($url,$param);
        $ret = array();

        if($result['code'] == 'OP_SUCCESS'){
            $ret['msg'] = "成功";
            $ret['code'] = 200;
            $ret['traceId'] = $result['traceId'];

            return $ret;
        }else{
            $ret['msg'] = $result['msg'];
            $ret['code'] = 199;
            return $ret;
        }

    }

    public function consume($order)
    {

        $url = "https://api-open-cater.meituan.com/ddzh/tuangou/receipt/consume";

        $userMtModel = new Usermeituancode();
        $userMtModel->where('mt_code', $order['mt_code'])->update(['status' => 'lock']);
        $userMeituanCode = new Usermeituancode();
        $shopModel = new Shop();
        $meituan = $userMeituanCode->where('mt_code', $order['mt_code'])->find();
        $shop = $shopModel->where('id', $meituan['shop_id'])->find();

        $code = $order['mt_code'];

        $param = array();
        $param['businessId'] = 58;
        $param['charset'] = "UTF-8";
        $param['appAuthToken'] = $shop['mt2_token'];
        $param['timestamp'] = time();
        $param['developerId'] = $this->developerId;
        $param['version'] = 2;

        $biz = array();
        $biz['receiptCode'] = $code;
        $biz['count'] = 1;
        $biz['requestId'] = $order['mt_trace_id'];
        $biz['appShopAccountName'] = "雀侠";
        $biz['appShopAccount'] = "quexia2000";



        $param['biz'] = json_encode($biz);
        $param['sign'] = $this->get_sign($this->signKey,$param);

        $result = $this->curl_post($url,$param);
        $isChecked = 0;

        if($result['code'] == 'OP_SUCCESS'){
            $isChecked = 1;
            $price = $result['data'][0]['dealPrice'];
            $payList = $result['data'][0]['paymentDetail'];

            foreach ($payList as $key => $val) {
                if ($val['amountType'] == 10 && $val['amount'] > 0) {
                    $price = $val['amount'];
                }
            }
            $tableOrderModel = new Shoptableorder();
            $db = $tableOrderModel->where('order_no', $order['order_no'])->find();
            if ($db) {
                $tableOrderModel->where('id', $order['id'])->update(['amount' => $price]);
            } else {
                $shopOrderModel = new Shoporder();
                $shopOrderModel->where('id', $order['id'])->update(['amount' => $price]);
            }

        }
        return $isChecked;
    }


    public function curl_post($url, $postdata)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检测
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Expect:'
        )); //
        $post_data = http_build_query($postdata);//重点

        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
// curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        $tmpInfo = json_decode($tmpInfo, true);
        return $tmpInfo;
    }


    function get_sign($sign_key, $data)
    {
        if ($data == null) {
            return null;
        }
        ksort($data);
        $result_str = "";
        foreach ($data as $key => $val) {
            if ( $key != null && $key != "" && $key != "sign" ) {
                $result_str = $result_str . $key . $val;
            }
        }
        $result_str = $sign_key . $result_str;


        $ret = bin2hex(sha1($result_str, true));

        return $ret;
    }


}
